import { createStore } from "vuex"; // 确保正确导入 createStore

export default createStore({
  state: {
    cartItems: [],
  },
  mutations: {
    addToCart(state, product) {
      const existingItem = state.cartItems.find(
        (item) => item.product_id === product.product_id
      );
      if (existingItem) {
        if (existingItem.quantity < existingItem.stock_quantity) {
          existingItem.quantity++;
        } else {
          console.warn("已达到库存上限");
        }
      } else {
        state.cartItems.push({
          ...product,
          quantity: 1,
          selected: false,
        });
      }
    },
    removeItem(state, product) {
      state.cartItems = state.cartItems.filter(
        (item) => item.product_id !== product.product_id
      );
    },
    updateQuantity(state, { product, change }) {
      const item = state.cartItems.find(
        (i) => i.product_id === product.product_id
      );
      if (item) {
        const newQuantity = item.quantity + change;
        if (newQuantity >= 1 && newQuantity <= item.stock_quantity) {
          item.quantity = newQuantity;
        }
      }
    },
  },
});
